<template>
  <el-dialog
    v-loading="loading"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    title="转化学员填写字段 "
    width="400px"
    @close="handleCancel"
    v-if="visible"
  >
    <div class="handle-box">
      <!-- <div class="handle-item">
        <div class="handle-item-name">销售微信：</div>
        <el-input
          v-model="wechat"
          show-word-limit
          type="text"
          placeholder="请输入销售微信"
        />
      </div> -->
      <div class="handle-item" v-show="isOne">
        <div class="handle-item-name">
          <span style="color: red" v-if="trainingRequest && trainingRequired"
            >*</span
          >
          训练营期数：
        </div>
        <el-input
          v-model="trainingPeriods"
          show-word-limit
          type="text"
          maxlength="9"
          oninput="value=value.replace(/[^\d]/g,'')"
          placeholder="请输入训练营期数"
        />
      </div>
      <div class="handle-item">
        <div class="handle-item-name">
          <span style="color: red" v-if="trainingRequest && teacherRequired"
            >*</span
          >营销讲师：
        </div>
        <user-select
          class="handle-item-content"
          :teacherList="transformTeacherList"
          v-model="teacherId"
          @input="user2Change"
          style="width: 100%"
        />
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click.native="handleCancel">取消</el-button>
      <el-button v-debounce="handleConfirm" type="primary">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { XhUserCell } from "@/components/CreateCom";
import { crmLeadsTransformAPI, queryTeacher } from "@/api/crm/leads";
import UserSelect from "@/views/admin/components/UserSelect"; // 人员选择器
import { queryLeadsFieldForTrainingAPI } from "@/api/admin/training";
export default {
  /** 学员管理 的 勾选后的 转移 操作*/
  name: "TransferHandle",
  components: {
    XhUserCell,
    UserSelect,
  },
  mixins: [],
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
      default: false,
    },
    /** 没有值就是全部类型 有值就是单个类型 */
    crmType: {
      type: String,
      default: "",
    },
    /** 转化数据 */
    selectionList: {
      type: Array,
      default: () => {
        return [];
      },
    },
    /** 课程讲师列表 */
    transformTeacherList: {
      type: Array,
      default: () => {
        return [];
      },
    },
  },
  data() {
    return {
      loading: false, // 加载动画
      visible: false,
      isOne: false,
      wechat: "",
      trainingPeriods: "",
      teacher: "",
      teacherList: [],
      trainingPeriods1: "",
      user: [],
      strucs: [],
      teacherId: "",
      teacherRequired: true, //课程讲师是否必填
      trainingRequired: true, //训练营期数是否必填
      trainingRequest: false, //请求是否结束
    };
  },
  computed: {
    // 是否展示移除操作类型
    showRemoveType() {
      if (
        this.crmType == "leads" ||
        this.crmType == "contacts" ||
        this.crmType == "receivables" ||
        this.crmType == "product" ||
        this.crmType == "invoice"
      ) {
        return false;
      }
      return true;
    },
  },
  watch: {
    dialogVisible: {
      handler(val) {
        this.visible = val;
        if (!val) {
          this.resetData();
        } else {
          this.getTrainingRequired();
          if (this.selectionList.length == 1) {
            this.trainingPeriods = this.selectionList[0].trainingPeriods;
          } else {
            this.trainingPeriods = "";
          }
        }
      },
      deep: true,
      immediate: true,
    },

    selectionList: {
      handler(val) {
        if (this.selectionList.length == 1) {
          // console.log("长度等于1");
          this.trainingPeriods = this.selectionList[0].trainingPeriods;
          if (this.selectionList[0].teacherId) {
            this.teacherId = Number(this.selectionList[0].teacherId);
          } else {
            this.teacherId = "";
          }

          this.isOne = true;
        } else {
          // console.log("this.selectionList");
          this.trainingPeriods = "";
          this.teacherId = "";
          this.isOne = false;
        }
      },
    },
  },
  mounted() {
    this.visible = this.dialogVisible;
    // this.getTeacherList();
  },
  methods: {
    getTrainingRequired() {
      queryLeadsFieldForTrainingAPI().then((res) => {
        this.trainingRequest = true;
        this.teacherRequired = res.data.teacherIdForNotNull == 1 ? true : false;
        this.trainingRequired =
          res.data.trainingPeriodsForNotNull == 1 ? true : false;
      });
    },
    user2Change(data) {
      this.teacherId = data;
    },
    userSelect(data) {
      if (data.value.length > 0) {
        this.teacherId = data.value[0].userId;
        // console.log(data.value[0].userId);
      } else {
        this.teacherId = "";
        // console.log("data.value.size = 0");
      }
    },
    /**
     * 重置信息
     */
    resetData() {
      this.usersList = [];
      this.removeType = 1; // 移动类型
      this.handleType = 1; // 操作类型
      this.addsTypes = []; // 添加至
    },
    async getTeacherList() {
      const res = await queryTeacher().catch((err) => {
        throw err;
      });
      if ((res.code = "0")) {
        this.teacherList = res.data;
      }
    },
    /**
     * 取消选择
     */
    handleCancel() {
      // console.log(this.selectionList, "close");
      this.visible = false;
      this.$emit("update:dialogVisible", false);
      this.wechat = "";
      this.trainingPeriods = "";
      this.teacher = "";
    },
    handleConfirm() {
      if (this.trainingRequired && this.isOne) {
        if (!this.trainingPeriods) {
          this.$message.error("训练营期数不能为空!");
          return;
        }
      }
      if (this.teacherRequired) {
        if (!this.teacherId) {
          this.$message.error("营销讲师不能为空!");
          return;
        }
      }

      this.loading = true;
      this.getRequest()(this.getParams())
        .then((res) => {
          this.$message({
            type: "success",
            message: "操作成功",
          });
          this.timer = setTimeout(() => {
            this.loading = false;
          }, 1500);
          this.handleCancel();

          // 刷新待办
          if (
            this.crmType == "customer" ||
            this.crmType == "contract" ||
            this.crmType == "leads"
          ) {
            this.$store.dispatch("GetMessageNum");
          }

          this.$emit("handle", { type: "transfer" });
        })
        .catch(() => {
          this.timer = setTimeout(() => {
            this.loading = false;
          }, 1500);
        });
    },
    getRequest() {
      if (this.crmType === "leads") {
        return crmLeadsTransformAPI;
      }
    },
    getParams() {
      var wechat = this.wechat;
      var trainingPeriods = this.trainingPeriods;
      var teacher = this.teacherId;
      var params = {
        // wechat: wechat,
        trainingPeriods: trainingPeriods,
        teacher: teacher,
      };
      params["leadsIds"] = this.selectionList.map((item) =>
        parseInt(item[this.crmType + "Id"])
      );

      return params;
    },
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
};
</script>

<style lang="scss" scoped>
.handle-box {
  color: #333;
  font-size: 12px;
}
.handle-item {
  // width: 260px;
  width: 100%;
  padding-bottom: 15px;
  .handle-item-name {
    width: 115px;
    margin-bottom: 10px;
    font-size: 12px;
    color: #666;
  }
  .handle-item-content {
    flex: 1;
  }
}
.handle-bar {
  position: relative;
  margin-top: 10px;
  height: 30px;
  button {
    float: right;
    margin-right: 10px;
  }
}
// .el-form {
//   /deep/ .el-form-item__label {
//     height: 30px;
//     line-height: 30px;
//     padding: 0;
//   }
// }

/deep/ .el-dialog__title {
  color: #000;
  font-weight: bold !important;
}

/deep/ .el-dialog__body {
  padding: 10px 20px;
  .el-form-item {
    margin: 0;
    padding: 0 20px 15px;
    background-color: #fff;
  }
}
/deep/ .el-dialog__footer {
  padding: 8px !important;
}
</style>
